const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const router = require("./routes/router");
const puppeteer = require("./utils/puppeteer");

onerror(app); //添加报错监听器

//post请求处理
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());
app.use(logger());
//静态资源
app.use(require("koa-static")(__dirname + "/public"));
//页面引擎
app.use(
  views(__dirname + "/views", {
    extension: "ejs",
  })
);

// 全局拦截配置CROS，允许跨域访问
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set(
    "Access-Control-Allow-Headers",
    "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , token"
  );
  ctx.set("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
  if (ctx.method == "OPTIONS") {
    ctx.body = 200;
  } else {
    await next();
  }
});

// 日志logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next().catch((err) => {
    console.log("err", err.status);
    throw err;
  });
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

router(app); //导入路由

//监听报错
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

app.context.launchBrowser = puppeteer.launchBrowser();

// app.listen(3002, () => {
//   console.log("koa-server start at 3001 port");
// });

module.exports = app;
